/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim;

import java.io.File;
import java.io.FileFilter;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.naming.Context;

import org.apache.log4j.Logger;

import au.com.lastweekend.jasc.AfterShotInfo;
import au.com.lastweekend.jasc.AlbumInfo;
import au.com.lastweekend.jim.imagebase.ExternalImporter;
import au.com.lastweekend.jim.imagebase.ImageBase;
import au.com.lastweekend.jim.imagebase.ImageBaseDirectory;
import au.com.lastweekend.jim.imagebase.ImageInfo;
import au.com.lastweekend.jim.imagebase.ImageManager;
import au.com.lastweekend.jim.imagebase.LDAPImageBase;
import au.com.lastweekend.jim.imagebase.SoftHashMap;
import au.com.lastweekend.jim.imagebase.TagHandler;
import au.com.lastweekend.jim.imagebase.TagHandlerFactory;
import au.com.lastweekend.jim.util.StringUtils;

/**
 * Uses afs.dbt files formatted like Windows INI files from the JASC Aftershot (now known as JASC Photo Album) to set title and
 * keyword information
 * 
 * @author grant@lastweekend.com.au
 * @version $Id: AFSImporter.java,v 1.7 2006/04/16 09:14:13 ggardner Exp $
 */
@SuppressWarnings("unchecked")
public class AFSImporter implements ExternalImporter {

    private static final Logger LOG = Logger.getLogger(AFSImporter.class);

    private Map<File, AlbumInfo> _dirMap = new SoftHashMap<File, AlbumInfo>();

    static String convertKey(String afsKey) {

        String doubleSlash = ImageBase.KEYWORD_SEPARATOR + ImageBase.KEYWORD_SEPARATOR;

        return afsKey.substring(1).replaceAll(ImageBase.KEYWORD_SEPARATOR, "-").replaceAll("/", ImageBase.KEYWORD_SEPARATOR)
                .replaceAll(doubleSlash, "/");
    }

    public void importExternalMetadata(File file, ImageBaseDirectory imageDirectory) {

        File dir = file.getAbsoluteFile().getParentFile();
        AfterShotInfo afsInfo;
        AlbumInfo albumInfo = getAlbumInfo(dir);
        if (albumInfo != null) {
            afsInfo = albumInfo.getInfo(file.getName());

            if (afsInfo != null) {
                String title = imageDirectory.getTitle();
                if (StringUtils.isBlank(title)) {
                    imageDirectory.setTitle(afsInfo.getTitle());
                }
                Set<String> keywords = new HashSet<String>();
                for (Iterator iter = afsInfo.getKeys().iterator(); iter.hasNext();) {
                    String afsKey = (String) iter.next();

                    String jimKey = convertKey(afsKey);
                    keywords.add(jimKey);
                }

                Set<String> convertKeys = keywords;
                convertKeys.addAll(imageDirectory.getKeywords());
                imageDirectory.setKeywords(convertKeys);
            }
        }
    }

    private AlbumInfo getAlbumInfo(File dir) {

        AlbumInfo albumInfo = _dirMap.get(dir);
        if (albumInfo == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Finding album for " + dir);
            }
            albumInfo = new AlbumInfo(dir);
            _dirMap.put(dir, albumInfo);
        }
        return albumInfo;
    }

    /**
     * AFSImporter <directory> [<excluded directory pattern>]
     * 
     * @param args
     */
    public static void main(String[] args) {

        File dir = new File(args[0]);
        Pattern excludedDirs;
        if (args.length > 1) {
            excludedDirs = Pattern.compile(args[1]);
        } else {
            excludedDirs = Pattern.compile(".*");
        }

        Map<String, String> env = new HashMap<String, String>();

        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, System.getProperty("jim.bind.dn", "cn=Manager, dc=lastweekend,dc=com,dc=au"));
        env.put(Context.SECURITY_CREDENTIALS, System.getProperty("jim.bind.pwd", "secret"));
        // Enable connection pooling
        env.put("com.sun.jndi.ldap.connect.pool", "true");

        ImageBase imageBase;

        // TODO (Ignore) Configure imagebase somehow.
        try {
            imageBase = new LDAPImageBase(env, System.getProperty("jim.ldap.url",
                    "ldap://localhost:389/ou=jim,dc=lastweekend,dc=com,dc=au"), getTagHandlerFactory());
        } catch (Exception e) {
            LOG.error("Could not connect to LDAP", e);
            return;
        }

        ImageManager imageManager = new ImageManager(imageBase, new AFSImporter());
        importDir(dir, imageManager, excludedDirs);

    }

    private static TagHandlerFactory getTagHandlerFactory() {

        return new TagHandlerFactory() {

            public TagHandler makeTagHandler(ImageBase imageBase, ImageBaseDirectory imageBaseDirectory) {

                return new TagHandler() {

                    public void setTag(int tagType, int formatCode, Object value) {

                        // Do nothing
                    }
                };
            }
        };
    }

    private static void importDir(File dir, ImageManager imageManager, final Pattern excludedDirs) {

        File[] subDirectories = dir.listFiles(new FileFilter() {

            public boolean accept(File pathname) {

                return pathname.isDirectory() && (!excludedDirs.matcher(pathname.getName()).matches());
            }
        });
        for (int i = 0; i < subDirectories.length; i++) {
            importDir(subDirectories[i], imageManager, excludedDirs);
        }

        Collection<ImageInfo> directoryImages = imageManager.getDirectoryImages(dir);
        for (ImageInfo imageInfo : directoryImages) {
            imageManager.importToImageBase(imageInfo);
        }
    }

}
